package cn.legend.travel.destination.keyword.service.impl;

import cn.legend.travel.destination.keyword.service.IKeywordService;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;
@Service
public class KeywordServiceImpl implements IKeywordService {
    @Autowired
    private RestHighLevelClient client;
    @Override
    public List<String> getSuggestion(String prefix) {
        try {
            SearchRequest request = new SearchRequest("destination_table");
            request.source().suggest(new SuggestBuilder().addSuggestion(
                    "pinyin",
                    SuggestBuilders.completionSuggestion("pinyin")
                            .prefix(prefix)
                            .skipDuplicates(true)
                            .size(15)
            ));
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            Suggest suggest = response.getSuggest();
            CompletionSuggestion mySuggestion = suggest.getSuggestion("pinyin");
            List<CompletionSuggestion.Entry.Option> options = mySuggestion.getOptions();
            return options.stream()
                    .map(t -> t.getText().toString())
                    .collect(Collectors.toList());
        } catch (IOException e) {
            throw new RuntimeException();
        }
    }
}
